//
//  ErDuFriendVC.m
//  BrushFace
//
//  Created by timer_q on 16/1/11.
//  Copyright © 2016年 Zzz. All rights reserved.
//

#import "CommonFriendVC.h"
#import "FriendListCell.h"
#import "NavHelper.h"
#import "pinyin.h"

@interface CommonFriendVC ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableDictionary                 *contactInfoDic;
    NSMutableArray                      *indexArray;
    UITableView                         *_tableView;
    NSArray                             *_currentArray;
}
@end

@implementation CommonFriendVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UIConfig];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navBar setTitle:[NSString stringWithFormat:@"我和%@",self.name]];
    if (_currentArray.count == 0) {
        _tableView.hidden = YES;
        [self.view bringSubviewToFront:self.nullLabel];
        return;
    }
    NSMutableDictionary*index=[NSMutableDictionary dictionaryWithCapacity:0];
    for (NSDictionary *dic in _currentArray) {
        NSString* str=dic[@"nickName"];
        str = [self replayBaseStr:str];
        //获得中文拼音首字母，如果是英文或数字则#
        NSString *strFirLetter = [NSString stringWithFormat:@"%c",pinyinFirstLetter([str characterAtIndex:0])];
        if ([strFirLetter isEqualToString:@"#"]) {
            //转换为小写
            strFirLetter= [self upperStr:[str substringToIndex:1]];
        }
        if ([[index allKeys]containsObject:strFirLetter]) {
            //判断index字典中，是否有这个key如果有，取出值进行追加操作
            [[index objectForKey:strFirLetter] addObject:dic];
        }else{
            NSMutableArray*tempArray=[NSMutableArray arrayWithCapacity:0];
            [tempArray addObject:dic];
            [index setObject:tempArray forKey:strFirLetter];
        }
    }
    
    contactInfoDic = index;
    indexArray = [[NSMutableArray alloc] init];
    for (NSString *key in index) {
        [indexArray addObject:key];
    }
    [_tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setFriendListWithArray:(NSArray *)array{
    _currentArray = array;
}
-(NSString*)upperStr:(NSString*)str{
    NSString *lowerStr = [str lowercaseStringWithLocale:[NSLocale currentLocale]];
    return lowerStr;
}

#pragma mark - customMethods
- (void)UIConfig{
    
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    
    self.view.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 65, SCREEN_WIDTH, SCREEN_HEIGHT-65) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    _tableView.sectionIndexColor = [UIColor grayColor];
    _tableView.sectionIndexBackgroundColor= [UIColor clearColor];
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];
    
}
#pragma mark - tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * header = [[UIView alloc] init];
    header.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(8, 0, 100, 30)];
    label.text = indexArray[section];
    [header addSubview:label];
    return header;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return indexArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[section]]] count];
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView == self.searchDisplayController.searchResultsTableView)
    {
        return nil;
    }
    return indexArray;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    //点击索引，列表跳转到对应索引的行
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseID = @"cellReuseID";
    FriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseID];
    if (cell == nil) {
        cell = [FriendListCell loadBundleNib];
        cell.backgroundColor = [UIColor whiteColor];
    }
    NSString *headerStr = [NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"userId"]];
    [cell.localImage sd_setImageWithURL:[NSURL URLWithString:headerStr] placeholderImage:nil];
    cell.nameLabel.text = [self replayBaseStr:[contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"nickName"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *friendId = [contactInfoDic objectForKey:[NSString stringWithFormat:@"%@",indexArray[indexPath.section]]][indexPath.row][@"userId"];
    NSLog(@"%@",friendId);
    [NavHelper gotoContactDetailVCWithUserId:friendId];
}

- (NSString *)replayBaseStr:(NSString *)nickName{
    NSMutableString *nickN = [[NSMutableString alloc]initWithString:nickName];
    NSMutableString *retStr = [[NSMutableString alloc] init];
    for (int i=0; i<nickN.length; i+=4) {
        NSString *subStr = [NSString stringWithFormat:@"\\u%@",[nickN substringWithRange:NSMakeRange(i, 4)]];
        [retStr appendString:[self replaceUnicode:subStr]];
    }
    return retStr;
}

- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

@end
